<template>
    <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit"
        @cancel="handleCancel">
        <BasicForm @register="registerForm" />

        <!--子表表格tab-->
        <a-tabs defaultActiveKey="1">
            <a-tab-pane tab="单项商品选择" key="1">
                <BasicTable @selection-change="selectionChange" @register="registerGoodsTable"
                    :rowSelection="rowGoodsSelection" :expandedRowKeys="expandedGoodsRowKeys"
                    @expand="handleGoodsExpand" @fetch-success="onFetchGoodsSuccess">
                </BasicTable>
            </a-tab-pane>

            <a-tab-pane tab="医院商品选择" key="2">
                <BasicTable @selection-change="selectionChange" @register="registerHospitalTable"
                    :rowSelection="rowHospitalSelection" :expandedRowKeys="expandedHospitalRowKeys"
                    @expand="handleHospitalExpand" @fetch-success="onFetchHospitalSuccess">
                </BasicTable>
            </a-tab-pane>

        </a-tabs>
    </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicTable } from '/@/components/Table';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from '../NursePromotional.data';
import { saveOrUpdate } from '../NursePromotional.api';
import { columns, searchFormSchema } from './NurseGoods.data';
import { list, getChildList, getChildListBatch } from './NurseGoods.api';
import { useListPage } from '/@/hooks/system/useListPage';
import { columns as hospitalcolumns, searchFormSchema as hospitalsearchFormSchema } from './NurseHospital.data';
import { list as hospitallist, getChildList as getChildhospitalList, getChildListBatch as getChildhospitalListBatch } from './NurseHospital.api';

const selectionChange = async ({ rows }) => {
    if (rows[0]) {
        const pName = rows[0].pName ? '[' + rows[0].pName + ']-' : ''
        const nurseType_dictText = rows[0].nurseType_dictText
        const hospital_dictText = rows[0].hospital_dictText ? '[' + rows[0].hospital_dictText + ']-' : ''
        const typeName = rows[0].typeName
        const goodsName = `[${nurseType_dictText}]-${hospital_dictText}${pName}[${typeName}]`
        await setFieldsValue({
            goodsId: rows[0].id,
            goodsName: goodsName,
            pid: rows[0].pid,
        });
    }
}

const queryGoodsParam = reactive<any>({ pid: "1", hospital: "0" });

const expandedGoodsRowKeys = ref([]);

const { tableContext: tableGoodsContext } = useListPage({
    tableProps: {
        api: list,
        title: '单项商品选择',
        columns,
        canResize: false,
        isTreeTable: true,
        rowSelection: { type: 'radio' }, //默认是 checkbox 多选，可以设置成 radio 单选
        formConfig: {
            //labelWidth: 120,
            schemas: searchFormSchema,
            autoSubmitOnEnter: true,
            showAdvancedButton: true,
            fieldMapToNumber: [
            ],
            fieldMapToTime: [
            ],
        },
        actionColumn: {
            width: 0,
            fixed: 'right'
        },
        beforeFetch: (params) => {
            return Object.assign(params, queryGoodsParam);
        },
    },

})

const [registerGoodsTable, { getDataSource: getGoodsDataSource }, { rowSelection: rowGoodsSelection, selectedRowKeys: selectedGoodsRowKeys }] = tableGoodsContext

/**
 *树节点展开合并
 * */
async function handleGoodsExpand(expanded, record) {
    // 判断是否是展开状态，展开状态(expanded)并且存在子集(children)并且未加载过(isLoading)的就去查询子节点数据
    if (expanded) {
        expandedGoodsRowKeys.value.push(record.id)
        if (record.children.length > 0 && !!record.children[0].isLoading) {
            let result = await getChildList({ pid: record.id });
            result = result.records ? result.records : result;
            if (result && result.length > 0) {
                record.children = getDataByGoodsResult(result);
            } else {
                record.children = null
                record.hasChild = '0'
            }
        }
    } else {
        let keyIndex = expandedGoodsRowKeys.value.indexOf(record.id)
        if (keyIndex >= 0) {
            expandedGoodsRowKeys.value.splice(keyIndex, 1);
        }
    }
}
function onFetchGoodsSuccess(result) {
    getDataByGoodsResult(result.items) && loadDataByGoodsExpandedRows();
}
function getDataByGoodsResult(result) {
    if (result && result.length > 0) {
        return result.map(item => {
            //判断是否标记了带有子节点
            if (item["hasChild"] == '1') {
                let loadChild = { id: item.id + '_loadChild', name: 'loading...', isLoading: true }
                item.children = [loadChild]
            }
            return item
        })
    }
}
async function loadDataByGoodsExpandedRows() {
    if (unref(expandedGoodsRowKeys).length > 0) {
        const res = await getChildListBatch({ parentIds: unref(expandedGoodsRowKeys).join(',') });
        if (res.success && res.result.records.length > 0) {
            //已展开的数据批量子节点
            let records = res.result.records
            const listMap = new Map();
            for (let item of records) {
                let pid = item['pid'];
                if (unref(expandedGoodsRowKeys).includes(pid)) {
                    let mapList = listMap.get(pid);
                    if (mapList == null) {
                        mapList = [];
                    }
                    mapList.push(item);
                    listMap.set(pid, mapList);
                }
            }
            let childrenMap = listMap;
            let fn = (list) => {
                if (list) {
                    list.forEach(data => {
                        if (unref(expandedGoodsRowKeys).includes(data.id)) {
                            data.children = getDataByGoodsResult(childrenMap.get(data.id))
                            fn(data.children)
                        }
                    })
                }
            };
            fn(getGoodsDataSource())
        }
    }
}

const queryHospitalParam = reactive<any>({ pid: "0" });

const expandedHospitalRowKeys = ref([]);

const { tableContext: tableHospitalContext } = useListPage({
    tableProps: {
        api: hospitallist,
        title: '医院商品选择',
        columns: hospitalcolumns,
        canResize: false,
        isTreeTable: true,
        rowSelection: { type: 'radio' }, //默认是 checkbox 多选，可以设置成 radio 单选
        formConfig: {
            //labelWidth: 120,
            schemas: hospitalsearchFormSchema,
            autoSubmitOnEnter: true,
            showAdvancedButton: true,
            fieldMapToNumber: [
            ],
            fieldMapToTime: [
            ],
        },
        actionColumn: {
            width: 0,
            fixed: 'right'
        },
        beforeFetch: (params) => {
            return Object.assign(params, queryHospitalParam);
        },
    },

})

const [registerHospitalTable, { getDataSource: getHospitalDataSource }, { rowSelection: rowHospitalSelection, selectedRowKeys: selectedHospitalRowKeys }] = tableHospitalContext

/**
 *树节点展开合并
 * */
async function handleHospitalExpand(expanded, record) {
    // 判断是否是展开状态，展开状态(expanded)并且存在子集(children)并且未加载过(isLoading)的就去查询子节点数据
    if (expanded) {
        expandedHospitalRowKeys.value.push(record.id)
        if (record.children.length > 0 && !!record.children[0].isLoading) {
            let result = await getChildhospitalList({ pid: record.id });
            result = result.records ? result.records : result;
            if (result && result.length > 0) {

                record.children = getDataByHospitalResult(result);

                record.children = record.children.map(item => {
                    return { ...item, pName: record.typeName }
                })
            } else {
                record.children = null
                record.hasChild = '0'
            }
        }
    } else {
        let keyIndex = expandedHospitalRowKeys.value.indexOf(record.id)
        if (keyIndex >= 0) {
            expandedHospitalRowKeys.value.splice(keyIndex, 1);
        }
    }
}
function onFetchHospitalSuccess(result) {

    getDataByHospitalResult(result.items) && loadDataByHospitalExpandedRows();
    setFieldsValue({
        goodsName: undefined,
    });
}
function getDataByHospitalResult(result) {
    if (result && result.length > 0) {

        return result.map(item => {

            //判断是否标记了带有子节点
            if (item["hasChild"] == '1') {
                let loadChild = { id: item.id + '_loadChild', name: 'loading...', isLoading: true }
                item.children = [loadChild]
            }
            return item
        })
    }
}
async function loadDataByHospitalExpandedRows() {

    if (unref(expandedHospitalRowKeys).length > 0) {
        const res = await getChildhospitalListBatch({ parentIds: unref(expandedHospitalRowKeys).join(',') });

        if (res.success && res.result.records.length > 0) {

            //已展开的数据批量子节点
            let records = res.result.records
            const listMap = new Map();
            for (let item of records) {
                let pid = item['pid'];

                if (unref(expandedHospitalRowKeys).includes(pid)) {
                    let mapList = listMap.get(pid);
                    if (mapList == null) {
                        mapList = [];
                    }

                    mapList.push(item);
                    listMap.set(pid, mapList);
                }
            }
            let childrenMap = listMap;
            let fn = (list) => {
                if (list) {
                    list.forEach(data => {
                        if (unref(expandedHospitalRowKeys).includes(data.id)) {
                            data.children = getDataByHospitalResult(childrenMap.get(data.id))
                            fn(data.children)
                        }
                    })
                }
            };
            fn(getHospitalDataSource())
        }
    }
}


// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    //labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 }
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ defaultFullscreen: true, confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
        //表单赋值

        await setFieldsValue({
            ...data.record,
        });
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter })
});
//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
//表单提交事件
async function handleSubmit(v) {
    try {
        let values = await validate();
        console.log("values", values)
        if (values.goodsId == '0') values.goodsName = '全部商品'

        setModalProps({ confirmLoading: true });
        //提交表单
        await saveOrUpdate(values, isUpdate.value);
        //关闭弹窗
        closeModal();
        //刷新列表
        emit('success');
    } finally {
        selectedHospitalRowKeys.value = []
        selectedGoodsRowKeys.value = []
        setModalProps({ confirmLoading: false });
    }
}

async function handleCancel() {

    selectedHospitalRowKeys.value = []
    selectedGoodsRowKeys.value = []
    setModalProps({ confirmLoading: false });

}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
    width: 100%
}

:deep(.ant-calendar-picker) {
    width: 100%
}
</style>